
$NG.AllReady(function (page, { useAction, useBeforeClick, useValuesChange, useClick, useUpdateRow, subscribe, useUpdateRows }) {
    const mstform = $NG.getCmpApi("BaseInfo")
    const toolbar = $NG.getCmpApi("CntMDetailToolBar")
    const dgrid1 = $NG.getCmpApi("ContractList")
    const user = $NG.getUser()
    const getHeadValue = (str) => mstform.getItem(str).getValue()
    const param = parseUrlParams(location.href)
    console.log(`param`, param);
    let counter = 0;

    setTimeout(()=>{
        // hiddenDetail(['ContractTerms','DeductionReward',])
    },200)

    if (!param.otype || param.otype == 'add') {
        mstform.getItem("PhidYsfl").setValue({
            label: '合同收入',
            value: "6870000000000016"
        })
        console.log(`增行`,);
        const rows = []
        const temp = ['预付款', '月进度合同款', '扣留（扣回）款', '返还款', '应支付款',]
        temp.forEach(item => {
            rows.push({
                ItemName: item,
                ItemResource: "freeadd",
                ItemNo: generateCode(),
                PhidFcur: "1",
                PhidFcur_EXName: "人民币",
                isGenNo: false,
                isNewOrModified: 1,
                AddType: 3,
                ResourceName: '合同外',
                OperFlg: 'cnt'
            })
        })
        dgrid1.addRows(rows)
    }

    // 添加按钮
    toolbar.insert({
        id: "open_cnt_js",
        text: "业主合同计量结算",
        iconCls: "icon-New"
    });
    toolbar.insert({
        id: "open_cnt_juesuan",
        text: "新承包合同决算",
        iconCls: "icon-New"
    });

    useClick(() => {
        const phid = mstform.getValues().PhId || "add"
        const BillName = mstform.getValues().BillName
        const origin = location.origin
        const url = `/view/contract/?v=${new Date().getTime()}#/CntPayM/list?AppTitle=${encodeURI("业主合同计量结算")}&menucode=e8d73471-a2f1-4858-5af3-45bb7cbb3cbe&multiCooperate=0&busCode=PCM_PAY1&cnt_id=${phid}&cnt_name=${BillName}`
        $NG.open(origin + url)
    }, "open_cnt_js")

    useClick(() => {
        const phid = mstform.getValues().PhId || "add"
        const BillName = mstform.getValues().BillName
        const origin = location.origin
        const url = `/view/contract/?v=${new Date().getTime()}#/CntFinalM/list?AppTitle=%E6%96%B0%E6%89%BF%E5%8C%85%E5%90%88%E5%90%8C%E5%86%B3%E7%AE%97&menucode=f2bf87de-c134-b642-2b11-6ed3351ca6a6&multiCooperate=0&busCode=PCM_FINAL_PAY1&cnt_id=${phid}&cnt_name=${BillName}`
        $NG.open(origin + url)
    }, "open_cnt_juesuan")

    useValuesChange(() => {
        console.log(`标段选择`,);
        getProjectInfoByPhid()
        getCntNo()
    }, "PhidPc")

    // 隐藏系统表单的明细标签
    function hiddenDetail(detailKey) {
        const page = detailKey.reduce((value, item) => {
            value.push($NG.getCmpApi(item))
            return value
        }, [])
        // 开始隐藏
        page.forEach(docker => {
            if (docker) {
                const bigDom = docker.getRef().bodyRef.current
                //向上查找父元素是否存在，向上查找3级
                let temp_pNode = bigDom.parentNode
                let pNode = null
                for (let level = 0; level < 9; level++) {
                    if (temp_pNode && temp_pNode.className?.replaceAll(" ","") == 'udp-full-page') {
                        pNode = temp_pNode
                        break
                    }
                    temp_pNode = temp_pNode.parentNode
                    console.log(`temp`, temp_pNode , temp_pNode.className);
                }
                if (pNode) {
                    pNode.style.display = 'none'
                } else {
                    console.log(`没找到`, page);
                }
            }
        })
    }


    // 解析URL
    function parseUrlParams(url) {
        const result = {};

        if (!url) return result;

        // 先拆出 ? 和 #
        const [beforeHash, hashPart] = url.split('#');

        // 处理 ? 部分
        if (beforeHash.includes('?')) {
            const queryStr = beforeHash.split('?')[1];
            queryStr.split('&').forEach(pair => {
                const [key, value] = pair.split('=');
                result[key] = decodeURIComponent(value || '');
            });
        }

        // 处理 # 后面的参数
        if (hashPart && hashPart.includes('?')) {
            const hashQueryStr = hashPart.split('?')[1];
            hashQueryStr.split('&').forEach(pair => {
                const [key, value] = pair.split('=');
                result[key] = decodeURIComponent(value || '');
            });
        }

        return result;
    }

    function getProjectInfoByPhid() {
        const phid = getHeadValue("PhidPc")
        if (!phid) return;
        $NG.execServer("getProjectInfoByPhid", { phid }, (res) => {
            if (res.count == 0) return
            const datas = JSON.parse(res.data)[0].extendObjects
            const values = [
                // {
                //     key:`BillNo`,
                //     value:datas.bill_no,
                // },
                {
                    key: `user_xmxz`,
                    value: datas.user_xmxz
                },
                {
                    key: `user_ywlb`,
                    value: {
                        label: datas.ywlb_name,
                        value: datas.user_ywlb
                    }
                },
                {
                    key: `user_sccyllb`,
                    value: {
                        value: datas.user_sccyllb,
                        label: datas.sccyllb_name
                    }
                },
                {
                    key: `user_yjhylb`,
                    value: {
                        value: datas.user_yjhylb,
                        label: datas.yjhylb_name
                    }
                },
                {
                    key: `user_ejhylb`,
                    value: {
                        value: datas.user_ejhylb,
                        label: datas.ejhylb_name
                    }
                },
                {
                    key: `CntSumVatFc`,
                    value: datas.approx_contract_fc
                },
                {
                    key: `SignDt`,
                    value: datas.user_htqdrj
                },
                {
                    key: `PhidCustomerEnt`,
                    value: {
                        value: datas.phid_company,
                        label: datas.jfdw_name//TODO
                    }
                },
                {
                    key: `user_ssjt`,
                    value: {
                        value: datas.user_ssjt,
                        label: datas.ssjt_name
                    }
                },
                {
                    key: `user_xmssdw2`,
                    value: {
                        value: datas.user_xmssdw,
                        label: datas.xmssdw_name
                    }
                },
                {
                    key: `PhidSupplyEnt`,
                    value: {
                        label: '中国水利水电第六工程有限公司',
                        value: 6870000000000001
                    }
                },

                {
                    key: `user_xmms`,
                    value: {
                        label: datas.xmms_name,
                        value: datas.user_xmms1
                    }
                },
                {
                    key: `user_xmszd`,
                    value: `${datas.sheng_name}-${datas.city_name}-${datas.qvxian_name}`
                },
                {
                    key: "user_zbrq",
                    value: datas.user_zbrq
                }
                , {
                    key: 'user_sfhztb',
                    value: datas.user_sfhztb
                }
            ]
            values.forEach(item => {
                mstform.getItem(item.key)?.setValue(item.value)
            })
            // 财务
            const cwForm = $NG.getCmpApi("FinancialInfo")
            const values_cw = [{
                key: `user_htjhkssj`,
                value: datas.start_date
            },
            {
                key: `user_htjhjssj`,
                value: datas.end_date
            },
            {
                key: `user_gq`,
                value: datas.limit_time
            },]
            values_cw.forEach(item => {
                cwForm.getItem(item.key)?.setValue(item.value)
            })
        })
    }

    // 拿到合同评审的合同编码
    function getCntNo() {
        const phid = mstform.getItem("PhidPc").getValue()
        if (!phid) return
        $NG.execServer("SELECT", { sql: `select bill_no from pcm3_cnt_checkup where phid_pc='${phid}'` }, (res) => {
            console.log(`获取编码`, res);
            if (res.count == 0) {
                $NG.alert("未找到业主合同评审，编码为空！")
                return
            }
            const datas = JSON.parse(res.data)[0].extendObjects
            mstform.getItem("BillNo").setValue(datas.bill_no)
        })
    }

    // 自增计数器，避免同毫秒内重复

    // 生成唯一编码函数
    function generateCode(prefix = '') {
        // 时间戳：年月日时分秒毫秒
        const now = new Date();
        const yyyy = now.getFullYear();
        const MM = String(now.getMonth() + 1).padStart(2, '0');
        const dd = String(now.getDate()).padStart(2, '0');
        const HH = String(now.getHours()).padStart(2, '0');
        const mm = String(now.getMinutes()).padStart(2, '0');
        const ss = String(now.getSeconds()).padStart(2, '0');
        const ms = String(now.getMilliseconds()).padStart(3, '0');

        // 2~3位随机数
        const random = Math.floor(Math.random() * 900) + 100; // 100-999

        // 自增值，3位，不够补0
        counter = (counter + 1) % 1000; // 0-999循环
        const cnt = String(counter).padStart(3, '0');

        return `${prefix}${yyyy}${MM}${dd}${HH}${mm}${ss}${ms}${random}${cnt}`;
    }
}, function () {



})